package com.ali.asyncgroup.context;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.util.concurrent.DefaultEventExecutorGroup;

public class AsyncGroupContextServer {
    //构建事件处理线程池
    private static final DefaultEventExecutorGroup defaultEventExecutorGroup = new DefaultEventExecutorGroup(16);

    public static void main(String[] args) {
        //构建连接线程池
        //构建处理线程池
        try (NioEventLoopGroup bossGroup = new NioEventLoopGroup(); NioEventLoopGroup workerGroup = new NioEventLoopGroup()) {
            //构建服务端启动对象
            ServerBootstrap serverBootstrap = new ServerBootstrap();
            //设置线程池
            serverBootstrap.group(bossGroup, workerGroup);
            //设置通道
            serverBootstrap.channel(NioServerSocketChannel.class);
            //设置处理器
            serverBootstrap.childHandler(new ChannelInitializer<SocketChannel>() {
                /**
                 * 通道初始化
                 */
                @Override
                protected void initChannel(SocketChannel socketChannel) {
                    //获取管道
                    ChannelPipeline channelPipeline = socketChannel.pipeline();
                    //添加处理器
                    channelPipeline.addLast(defaultEventExecutorGroup, new MyAsyncGroupContextServerHandler());
                }
            });
            //绑定监听端口，同步阻塞，等待操作完成
            ChannelFuture channelFuture = serverBootstrap.bind(8080).sync();
            //监听关闭通道，同步阻塞，等待操作完成
            channelFuture.channel().closeFuture().sync();
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }
    }
}
